package gi18n

import (
	"egin/pkg/config"
	"encoding/json"
	"encoding/xml"

	"github.com/BurntSushi/toml"
	"github.com/gin-gonic/gin"
	"gopkg.in/yaml.v2"

	"github.com/nicksnyder/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

var bundle *i18n.Bundle
var local *i18n.Localizer

func init() {

	bundle = i18n.NewBundle(language.English)

	types := config.C().Language.Type
	switch types {
	case "json":
		bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
	case "yaml":
		bundle.RegisterUnmarshalFunc("yaml", yaml.Unmarshal)
	case "toml":
		bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
	case "xml":
		bundle.RegisterUnmarshalFunc("xml", xml.Unmarshal)
	default:
		panic("Support json, yaml, toml, xml")

	}

	lang := config.C().Language.Lang
	path := config.C().Language.Path
	for _, v := range lang {
		bundle.MustLoadMessageFile(path + v + "." + types)
	}

}

func I18nMiddleware() gin.HandlerFunc {

	// i18nOnce.Do(I18nInit)

	return func(c *gin.Context) {
		var lang string

		var err error

		url_parameter_name := config.C().Language.UrlParameterName
		header_parameter_name := config.C().Language.HeaderParameterName

		accept := c.GetHeader("Accept-Language")

		lang = c.GetHeader(header_parameter_name)
		if lang == "" {
			lang = c.Query(url_parameter_name)
			if lang == "" {
				lang, err = c.Cookie("lang")
				if err != nil || lang == "" {
					lang = config.C().Language.Default
				}
			}
		}

		c.SetCookie("lang", lang, 0, "/", "", false, false)

		local = i18n.NewLocalizer(bundle, lang, accept)
		c.Next()
	}
}

func Lang(str string) string {

	return local.MustLocalize(&i18n.LocalizeConfig{MessageID: str})
}

func LangT(str string, mapString map[string]string) string {

	return local.MustLocalize(&i18n.LocalizeConfig{
		MessageID:    str,
		TemplateData: mapString,
	})
}

func LangL(lc *i18n.LocalizeConfig) string {

	return local.MustLocalize(lc)
}
